import React from 'react';
import { Upload, message } from 'antd';
import { useState } from 'react';
//import { usePuteditavaterMutation } from '../../store/request/accountrequest';
import { useDispatch, useSelector } from 'react-redux';
import reqwest from 'reqwest';
import { setLoginState } from '../../store/slice/loginslice';



const AvaterEdit = () => {
  const webapiavarterpath = window.app + "AvarterUpload/";
  const [imageUrl, setImageUrl] = useState();
  const loginstate = useSelector(state => state.loginpara);

  const dispatch = useDispatch();
  const [messageApi, contextHolder] = message.useMessage();
  //const [edittrigger, editresult] = usePuteditavaterMutation();


  const messageerror = (reason) => {
    //message.success('This is a success message');
    messageApi.open({
      type: 'error',
      content: '上传头像失败' + reason,
    });

  };
  const messagesucess = () => {
    messageApi.open({
      type: 'success',
      content: '上传头像成功',
    });
  };

  const props = {
    name: "avatar",
    showUploadList: false,//设置只上传一张图片，根据实际情况修改
    customRequest: info => {//手动上传
      const formData = new FormData();

      formData.append('avatar', info.file);//名字和后端接口名字对应
      formData.append('loginname', loginstate.role.loginname)
      //console.log(formData);
      reqwest({
        url: window.app + 'Account/Upload',//上传url
        method: 'post',
        processData: false,
        data: formData,
        success: (res) => {//上传成功回调
          //console.log(res);
          if (res.code === 200) {
            //这是在此页面显示最新上传的图像
            setImageUrl(window.app + "AvarterUpload/" + res.data.avatarpath);
            dispatch(setLoginState(res.data));
            messagesucess();
          }
          else {
            messageerror(res.data);
          }
        },
        error: () => {//上传失败回调
          messageerror('上传失败！');
        },
      });
    },

    listType: "picture-card",
    className: "avatar-uploader",

    beforeUpload: file => {//控制上传图片格式
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

      if (!isJpgOrPng) {
        message.error('您只能上传JPG/PNG 文件!');
        return;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小必须小于2MB!');
        return;
      }
      return isJpgOrPng && isLt2M;
    },
  };




  return (
    <>
      {contextHolder}
      <Upload {...props}

      >
        <img
          src={imageUrl ? imageUrl : webapiavarterpath + loginstate.role.avatarpath}
          alt="avatar"
          style={{
            width: '100%',
          }}
        />

      </Upload>

    </>
  )


}


export default AvaterEdit





